import React, { useState, startTransition, useEffect } from 'react'
import { Button, SearchBar, Space,Swiper, Toast,Ellipsis } from 'antd-mobile'
import { SearchOutline, SetOutline } from 'antd-mobile-icons'

import { Refresh,Add,Order,Star,Loading2 } from '@nutui/icons-react'

import { Navigate, useNavigate } from 'react-router-dom'
import { BackTop, Cell,FixedNav  } from '@nutui/nutui-react'
import '@nutui/nutui-react/dist/style.css'
import '../css/Main.css'
import ButtomBar from '../../sjc/components/ButtomBar'
import axios from 'axios'

const colors = [
'https://img.axureshop.com/54/93/61/54936165943d4fa7998606ae0844d36e/images/%E9%A6%96%E9%A1%B5%EF%BC%88%E5%B7%B2%E7%99%BB%E5%BD%95%EF%BC%89/u890.png',
'https://img.axureshop.com/54/93/61/54936165943d4fa7998606ae0844d36e/images/%E9%A6%96%E9%A1%B5%EF%BC%88%E5%B7%B2%E7%99%BB%E5%BD%95%EF%BC%89/u889.png',
'https://img.axureshop.com/54/93/61/54936165943d4fa7998606ae0844d36e/images/%E9%A6%96%E9%A1%B5%EF%BC%88%E5%B7%B2%E7%99%BB%E5%BD%95%EF%BC%89/u887.png',
'https://img.axureshop.com/54/93/61/54936165943d4fa7998606ae0844d36e/images/%E9%A6%96%E9%A1%B5%EF%BC%88%E5%B7%B2%E7%99%BB%E5%BD%95%EF%BC%89/u888.png'
]

const items = colors.map((color, index) => (
  <Swiper.Item key={index}>
    <div
      className='tu'
      style={{ backgroundImage:'url('+color+')',backgroundSize:'100% 100%'}}
    >
    </div>
  </Swiper.Item>))

export default function Main() {
  // let tuls=[<Refresh />, <Order />, <Star />]
  const list = [
    {
      id: 1,
      text: '刷新',
      icon: <Refresh />,
    },
    {
      id: 2,
      text: '订单',
      icon: <Order />,
    },
    {
      id: 3,
      text: '收藏',
      icon: <Star />,
    },
    {
      id: 4,
      z: '设置',
      icon:<Add/>,
    },
  ]
  
  const [visible, setVisible] = useState(false)
  const change = (value: boolean) => {
    setVisible(value)
  }
  const selected = (
    item: any,
    event: React.MouseEvent<Element, MouseEvent>
  ) => {
    if (item.text =='刷新') {
      window.location.reload()
    }else if (item.text == '收藏') {
      nav('/collection')
    }else if (item.text == '订单') {
      nav('/myorder', {state:{state: '全部'}})
    }else if (item.z == '设置') {
      nav('/gnye')
    }
  }
  let nav=useNavigate()
  let [ls, setLs] = useState([])
  let [live, setLive] = useState(JSON.parse(localStorage.getItem('live')) || [])
  let [zu, setZu] = useState([])
  let [snum, setSnum] = useState([])
  let [sls, setSls] = useState([])
  let show=()=>{
    let accessToken = localStorage.getItem("AccessToken")
    axios.get('/szh/showgoods',{
      headers: { "Authorization": `Bearer ${accessToken}` }
    }).then(res => {
      
      if(res.data.code === 401) {
        // refreshToken();
        return
      }
      setLs(res.data.gols)
      setSls(res.data.gols.slice(0,8))
      let szu=[]
      randomNumbers.map(i=>{
        szu.push(res.data.gols[i])
        setSls(szu)
      })
    })
  }
  let [a, setA] = useState([{ty:'体恤',num:0},{ty:'大衣',num:0}])
  let addlv=(i)=>{
    // a.map((x,index)=>{
      // console.log(x.ty);
      if(a.some(x=>x.ty==i)){
            console.log('重复');
            let xls=[...a]
            xls[a.findIndex(x=>x.ty==i)].num++
            setA(xls)
            localStorage.setItem('live',JSON.stringify(a))
          }else{
            // a.push({i:0})
            let xls=[...a]
            xls.push({ty:i,num:0})
            setA(xls)
            localStorage.setItem('live',JSON.stringify(a))
          }
    // })
    
  }
  let itm=(i)=>{
    
    nav('/item')
    addlv(i.type)
    localStorage.setItem('good',JSON.stringify(i))
  }
 
  const [randomNumbers, setRandomNumbers] = useState([]);
  const generateNumbers = () => {
    const numbers = new Set();
    while (numbers.size < 8) {
      numbers.add(Math.floor(Math.random() * 11) + 1);
    }
    setRandomNumbers([...numbers]);
  };
  let refreshToken = async () => {
    const refreshToken = localStorage.getItem("RefreshToken")
    let { code, token } = (await axios.get("/yzk/refresh_token", {
      headers: { "Authorization": `Bearer ${refreshToken}` }
    })).data
    if (code === 401) {
      alert("登陆失败")
      // 返回登陆界面
      nav("/")
      return
    } else {
      // 设置新的段token
      console.log(token);
      localStorage.setItem("AccessToken", token.accessToken)
      // 重新获取数据
      show()
    }}
   
  useEffect(() => {
    show()
    const generateNumbers = () => {
      const numbers = new Set();
      while (numbers.size < 8) {
        numbers.add(Math.floor(Math.random() * 11) + 1);
      }
      setRandomNumbers([...numbers]);
    };
    generateNumbers();
  },[])
  
  return (
    <div>
      <FixedNav
        list={list}
        type="left"
        position={{ bottom: '80px' }}
        visible={visible}
        activeText="功能"
        inactiveText="功能"
        onChange={change}
        onSelect={selected}
      />
      <BackTop threshold={200} style={{
        position: 'fixed',
        right: '10px',
        bottom: '150px',
        width: '50px',
        height: '50px',
        opacity: 0.6
      }}>
        <div
          style={{
            position: 'fixed',
            right: '20px',
            bottom: '157px',
            zIndex: 9999
          }}
          onClick={()=>{
            console.log(randomNumbers)
            generateNumbers();
            show()
            console.log(sls)
          }}
        >
          <Refresh width={16} height={16} />
          <div style={{ fontSize: '15px',marginLeft:'-6px'}}>刷新</div>
        </div>
      </BackTop>
        <div style={{width:'100%',height:'56px',background:'#fff',zIndex:'999',position:'fixed',top:'0px',left:'0px'}}>
            <br />
           <div style={{width:'94%',height:'40px',background:'#fff',margin:'auto'}}>
            <SearchBar
            onFocus={()=>{
              nav('/search')
            }}
            placeholder='请输入内容'
            style={{ '--background': '#eae9e5', width: '80%','--border-radius': '20px',float:'left' }}
            />
            <button onClick={()=>{startTransition(()=>Navigate('/signin'))}} style={{width:'50px',height:'32px',float:'right',borderRadius:'20px',border:'1px solid #c1ab96',background:'#fff',color:'#c1ab96'}}>签到</button>
            </div> 
        </div>
        <div style={{width:'100%',height:'56px'}}></div>
        <div style={{width:'100%',height:'120px'}}>
        <Swiper
          loop
          autoplay
        >
          {items}
        </Swiper>
        </div>
        <br />
        <br />
        <br />
        <br />
        <div style={{width:'100%',height:'60px',background:'#fff',display:'flex',justifyContent:'space-around',alignItems:'center'}}>
            <div onClick={()=>{
              nav('/gnye')
            }} style={{width:'33%',height:'60px',background:'#fff',textAlign:'center',lineHeight:'60px'}}><span style={{color:'#71a394',fontSize:'14px',fontWeight:'bold'}}>
              更多功能
            </span></div>
            <div onClick={()=>{nav('/pye')}} style={{width:'33%',height:'60px',background:'#fff',textAlign:'center',lineHeight:'60px'}}><span style={{color:'#71a394',fontSize:'14px',fontWeight:'bold'}}>人气店铺</span></div>
            <div style={{width:'33%',height:'60px',background:'#fff',textAlign:'center',lineHeight:'60px'}}><span style={{color:'#71a394',fontSize:'14px',fontWeight:'bold'}}>分类</span></div>
        </div>
        <div style={{width:"100%",height:'1070px',background:'#c1ab96',margin:'auto'}}>
            <div style={{width:"94%",height:'1050px',background:'#c1ab96',margin:'auto'}}>
                <br />
            <h3 style={{color:'white'}}>为您推荐</h3>
            <div>
              {sls.map(i=>{
                return <div onClick={()=>{itm(i)}} key={i._id} style={{width:'45%',height:'230px',border:'1px solid #ccc',
                background:'white',float:'left',margin:'8px',borderRadius:'6px',boxShadow:'0px 0px 4px #000'}}>
                  <img src={i.img[0]} style={{width:'100%',height:'150px',borderRadius:'6px'}}/>
                  <div style={{width:'90%',margin:'auto'}}>
                    <Ellipsis direction='end' rows={2} content={i.name} />
                  <div style={{width:'60px',height:'14px',borderTop:'1px solid #ccc',float:'left',
                  borderLeft:'1px solid #ccc',borderBottom:'1px solid #ccc',borderRight:'1px dashed #ccc'}}>
                    <span style={{fontSize:'11px',color:'#8e7e6f'}}>满300减30</span>
                  </div>  
                  <div style={{width:'50px',height:'14px',borderTop:'1px solid #ccc',float:'left',
                  borderLeft:'1px dashed #ccc',borderBottom:'1px solid #ccc',borderRight:'1px solid #ccc'}}>
                    <span style={{fontSize:'11px',color:'#8e7e6f'}}>店铺领劵</span>
                  </div>
                  <span style={{fontSize:'14px',fontWeight:'1000'}}>￥{i.price}</span>
                  </div>
                   
                </div>
              })}
            </div>
            </div>
        </div>
    </div>
  )
}
